<template>
  <div>
    <div class="table-page-search-wrapper">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="16">
          <a-form layout="inline" :model="listQuery">
            <a-form-item label="角色名称">
              <a-input v-model:value="listQuery.title" placeholder="请输入角色名称" />
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model:value="listQuery.status" placeholder="请选择">
                <a-select-option key="0" value="0">全部</a-select-option>
                <a-select-option key="1" value="1">正常</a-select-option>
                <a-select-option key="-1" value="-1">禁用</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchSubmit"> 搜索 </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="8">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新列表</span>
              </template>
              <a-button @click="reloadList">
                <template #icon><SyncOutlined /></template>
              </a-button>
            </a-tooltip>
            <a-button
              v-permission="{ action: 'role_add' }"
              type="primary"
              style="margin-left: 12px"
              @click="addNewData"
            >
              <template #icon><PlusOutlined /></template> 新增角色
            </a-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-table
      :columns="columns"
      :rowKey="(record) => record.id"
      :dataSource="dataList.list"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #status="{ text: record }">
        <a-tag v-if="record == 1" color="blue">正常</a-tag>
        <a-tag v-if="record == -1" color="red">禁用</a-tag>
      </template>
      <template #action="{ text: record }">
        <a v-permission="{ action: 'role_add' }" @click="role_edit(record)"
          ><EditOutlined /> 编辑</a
        >
        <a-divider v-permission="{ action: 'role_ext' }" type="vertical" />
        <a-dropdown>
          <a v-permission="{ action: 'role_ext' }" class="ant-dropdown-link">
            更多 <DownOutlined />
          </a>
          <template #overlay>
            <a-menu>
              <a-menu-item v-permission="{ action: 'role_fbid' }">
                <a @click="role_fbid(record)"> 禁用</a>
              </a-menu-item>
              <a-menu-item v-permission="{ action: 'role_unfbid' }">
                <a @click="role_unfbid(record)"> 解禁</a>
              </a-menu-item>
              <a-menu-item v-permission="{ action: 'role_del' }" style="color: red">
                <a @click="role_delete(record)"><DeleteOutlined /> 删除</a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-table>
    <a-modal
      v-model:visible="visible"
      :confirmLoading="confirmLoading"
      :title="operateTitle"
      style="top: 20px"
      :width="800"
      okText="提交"
      @ok="handleOk"
      @cancel="reloadList"
    >
      <a-form ref="formRef" :model="modalFormRef">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="角色名称"
          has-feedback
          required
          name="title"
          v-bind="validateInfos.title"
        >
          <a-input v-model:value="modalFormRef.title" placeholder="请输入角色名称" />
          <a-input v-model:value="modalFormRef.id" name="id" type="hidden" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="角色说明"
          has-feedback
          name="desc"
          v-bind="validateInfos.desc"
        >
          <a-textarea v-model:value="modalFormRef.desc" placeholder="说明" :rows="4" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="状态"
          has-feedback
          required
          name="status"
          v-bind="validateInfos.status"
        >
          <a-radio-group v-model:value="modalFormRef.status" name="status">
            <a-radio :key="1" :value="1">正常</a-radio>
            <a-radio :key="-1" :value="-1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-divider />
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态" required>
          <a-tree
            v-model:checkedKeys="modalFormRef.checkedKeys"
            :treeData="dataList.access"
            checkable
            defaultExpandAll
            class="scroll"
            @check="checkedKeyEven"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { IconFont } from '@/components/iconfont'
import { defineComponent, reactive, toRefs, onMounted, ref, toRaw } from 'vue'
import { Row, Col, Divider, Modal, Tree, Form } from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  PlusCircleOutlined,
  CopyOutlined,
  DownOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { requestSuccess, requestFailed } from '@/utils/feedback'
import { addData, editData, getRoleList, getRoleInfo, forbidItem, delItem } from '@/api/manage'

export default defineComponent({
  name: 'RoleList',
  components: {
    IconFont,
    SyncOutlined,
    PlusOutlined,
    EditOutlined,
    DownOutlined,
    PlusCircleOutlined,
    CopyOutlined,
    DeleteOutlined,
    [Row.name]: Row,
    [Col.name]: Col,
    [Divider.name]: Divider,
    [Tree.name]: Tree
  },
  setup() {
    const formRef = ref()
    const state = reactive({
      loading: true,
      dataList: [],
      treeData: [],
      state: {
        smsSendBtn: false,
        time: 60
      },
      visible: false,
      confirmLoading: false,
      operateTitle: '编辑',
      listQuery: {
        type: '0',
        status: '0',
        pageNo: 1,
        pageSize: 12,
        title: ''
      },
      mdl: {
        id: 0,
        status: '1'
      },
      pagination: {
        pageSizeOptions: ['10', '20', '30'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 10
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      columns: [
        {
          title: '角色名称',
          dataIndex: 'title'
        },
        {
          title: '角色说明',
          dataIndex: 'desc'
        },
        {
          title: '状态',
          dataIndex: 'status',
          slots: { customRender: 'status' }
        },
        {
          title: '操作',
          width: '250px',
          slots: { customRender: 'action' }
        }
      ]
    })
    const modalFormRef = reactive({
      id: '',
      title: '',
      desc: '',
      operate_type: 'edit',
      status: '',
      checkedKeys: [],
      halfKey: '',
      rules: '',
      halfrules: '',
      halfKeys: []
    })
    const modalRule = reactive({
      id: [
        {
          required: false,
          type: 'number'
        }
      ],
      rules: [
        {
          required: false,
          type: 'string'
        }
      ],
      halfrules: [
        {
          required: false,
          type: 'string'
        }
      ],
      title: [
        {
          required: true,
          message: '请输入角色名',
          trigger: ['blur', 'change']
        }
      ],
      desc: [
        {
          required: true,
          message: '请输入角色说明',
          trigger: ['blur', 'change']
        }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: ['blur', 'change'], type: 'number' }
      ]
    })
    const { resetFields, validate, validateInfos } = Form.useForm(modalFormRef, modalRule)
    onMounted(() => {
      getDataList()
    })

    function handleTableChange(e) {
      state.loading = true
      state.listQuery.pageSize = e.pageSize
      state.listQuery.pageNo = e.current
      getDataList()
    }

    function reloadList() {
      state.loading = true
      state.listQuery.pageNo = 1
      getDataList()
    }

    function searchSubmit() {
      state.loading = true
      getDataList()
    }

    function getDataList() {
      getRoleList(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
      })
    }

    function role_edit(itemData) {
      state.operateTitle = '编辑角色'
      modalFormRef.operate_type = 'edit'
      getRoleInfo({ id: itemData.id }).then((res) => {
        modalFormRef.checkedKeys = res.rules
        modalFormRef.halfKeys = res.halfrules
      })
      state.visible = true
      resetFields()
      if (itemData !== undefined && itemData) {
        for (let item in itemData) {
          if (item !== 'rules') {
            modalFormRef[item] = itemData[item]
          }
        }
        modalFormRef.operate_type = 'edit'
      }
    }
    function addNewData() {
      state.operateTitle = '新增权限组'
      modalFormRef.operate_type = 'add'
      state.visible = true
      resetFields()
    }
    function checkedKeyEven(v, e) {
      modalFormRef.halfKeys = e.halfCheckedKeys
    }
    function role_fbid(data) {
      Modal.confirm({
        title: '确认禁用此角色?',
        content: '【' + data.title + '】',
        okType: 'danger',
        onOk() {
          forbidItem({ id: data.id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              reloadList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function role_unfbid(data) {
      Modal.confirm({
        title: '确认解除禁用?',
        content: '【' + data.title + '】',
        okType: 'danger',
        onOk() {
          forbidItem({ id: data.id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              reloadList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function role_delete(data) {
      Modal.confirm({
        title: '确认永久删除以下角色?',
        content: '【' + data.title + '】',
        okType: 'danger',
        onOk() {
          delItem({ id: data.id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              reloadList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function handleOk() {
      validate()
        .then(() => {
          let formRaw = toRaw(modalFormRef)
          state.confirmLoading = true
          formRaw.rules = modalFormRef.checkedKeys.join(',')
          formRaw.halfKey = modalFormRef.halfKeys.join(',')
          if (modalFormRef.operate_type === 'edit') {
            editData(formRaw).then((res) => {
              state.confirmLoading = false
              if (res.code === 200) {
                state.visible = false
                reloadList()
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
          } else if (modalFormRef.operate_type === 'add') {
            addData(formRaw).then((res) => {
              state.confirmLoading = false
              if (res.code === 200) {
                state.visible = false
                requestSuccess(res)
                reloadList()
              } else {
                requestFailed(res)
              }
            })
          }
        })
        .catch((err) => {
          console.log(err)
          return false
        })
    }
    return {
      ...toRefs(state),
      handleTableChange,
      reloadList,
      checkedKeyEven,
      searchSubmit,
      role_delete,
      formRef,
      modalRule,
      addNewData,
      role_edit,
      modalFormRef,
      validateInfos,
      role_unfbid,
      role_fbid,
      handleOk,
      getDataList
    }
  }
})
</script>

<style scoped></style>
